// 知识库管理API接口
import type { Article, Category, GetArticlesParams, KnowledgeStats } from '../types/knowledge';
import { http, getAPI_BASE_URL_SYNC } from '../lib/http-client';
import { shouldUseMockServer } from '../config/app.config';
import { articleData, categoryData } from '../data/knowledgeData';

// 知识库API基础路径
const KNOWLEDGE_API_BASE = `${getAPI_BASE_URL_SYNC()}/knowledge`;

// API响应接口
export interface ApiResponse<T> {
  data: T;
  total: number;
  success: boolean;
  message?: string;
}

// 后端API响应格式（根据实际后端API调整）
interface BackendApiResponse<T> {
  code: number;
  message: string;
  data: T;
  total?: number;
  success?: boolean;
}

// 文章列表响应格式
interface ArticleListResponse {
  articles: Article[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 分类列表响应格式
interface CategoryListResponse {
  categories: Category[];
  total: number;
}

// 知识库模拟API实现
const mockKnowledgeApi = {
  async getArticles(params: GetArticlesParams = {}): Promise<ApiResponse<Article[]>> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const { page = 1, pageSize = 10, search, category, status, author, sortBy = 'createdAt', sortOrder = 'desc' } = params;
    
    // 过滤数据
    let filteredData = [...articleData];
    
    if (search) {
      filteredData = filteredData.filter(article => 
        article.title.toLowerCase().includes(search.toLowerCase()) ||
        article.content.toLowerCase().includes(search.toLowerCase()) ||
        article.summary?.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    if (category) {
      filteredData = filteredData.filter(article => article.category === category);
    }
    
    if (status) {
      filteredData = filteredData.filter(article => article.status === status);
    }
    
    if (author) {
      filteredData = filteredData.filter(article => article.author === author);
    }
    
    // 排序
    filteredData.sort((a, b) => {
      let aValue: any, bValue: any;
      
      switch (sortBy) {
        case 'viewCount':
          aValue = a.viewCount;
          bValue = b.viewCount;
          break;
        case 'likeCount':
          aValue = a.likeCount;
          bValue = b.likeCount;
          break;
        case 'updatedAt':
          aValue = new Date(a.updatedAt).getTime();
          bValue = new Date(b.updatedAt).getTime();
          break;
        default:
          aValue = new Date(a.createdAt).getTime();
          bValue = new Date(b.createdAt).getTime();
      }
      
      return sortOrder === 'asc' ? aValue - bValue : bValue - aValue;
    });
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    return {
      data: paginatedData,
      total: filteredData.length,
      success: true,
      message: '获取文章列表成功'
    };
  },

  async createArticle(articleData: Partial<Article>): Promise<ApiResponse<Article>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const newArticle: Article = {
      id: Date.now(),
      title: articleData.title || '',
      content: articleData.content || '',
      category: articleData.category || '使用指南',
      tags: articleData.tags || [],
      author: articleData.author || '',
      status: articleData.status || '草稿',
      viewCount: 0,
      likeCount: 0,
      commentCount: 0,
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0],
      attachments: articleData.attachments || [],
      summary: articleData.summary || ''
    };
    
    articleData.push(newArticle);
    
    return {
      data: newArticle,
      total: 1,
      success: true,
      message: '文章创建成功'
    };
  },

  async updateArticle(articleId: number, articleData: Partial<Article>): Promise<ApiResponse<Article>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = articleData.findIndex(article => article.id === articleId);
    if (index === -1) {
      throw new Error('文章不存在');
    }
    
    articleData[index] = { 
      ...articleData[index], 
      ...articleData, 
      updatedAt: new Date().toISOString().split('T')[0] 
    };
    
    return {
      data: articleData[index],
      total: 1,
      success: true,
      message: '文章信息更新成功'
    };
  },

  async deleteArticle(articleId: number): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = articleData.findIndex(article => article.id === articleId);
    if (index === -1) {
      throw new Error('文章不存在');
    }
    
    articleData.splice(index, 1);
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '文章删除成功'
    };
  },

  async getCategories(): Promise<ApiResponse<Category[]>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    return {
      data: categoryData,
      total: categoryData.length,
      success: true,
      message: '获取分类列表成功'
    };
  },

  async getKnowledgeStats(): Promise<ApiResponse<KnowledgeStats>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const stats: KnowledgeStats = {
      totalArticles: articleData.length,
      publishedArticles: articleData.filter(article => article.status === '已发布').length,
      draftArticles: articleData.filter(article => article.status === '草稿').length,
      totalViews: articleData.reduce((sum, article) => sum + article.viewCount, 0),
      totalLikes: articleData.reduce((sum, article) => sum + article.likeCount, 0),
      totalComments: articleData.reduce((sum, article) => sum + article.commentCount, 0),
      categoryCount: categoryData.length
    };
    
    return {
      data: stats,
      total: 1,
      success: true,
      message: '获取知识库统计成功'
    };
  }
};

export const knowledgeApi = {
  // 获取文章列表（支持分页、搜索、筛选、排序）
  async getArticles(params: GetArticlesParams = {}): Promise<ApiResponse<Article[]>> {
    if (shouldUseMockServer()) {
      return mockKnowledgeApi.getArticles(params);
    }
    try {
      const { page = 1, pageSize = 10, search, category, status, author, sortBy, sortOrder } = params;
      
      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString()
      });
      
      if (search) queryParams.append('search', search);
      if (category) queryParams.append('category', category);
      if (status) queryParams.append('status', status);
      if (author) queryParams.append('author', author);
      if (sortBy) queryParams.append('sortBy', sortBy);
      if (sortOrder) queryParams.append('sortOrder', sortOrder);
      
      const url = `${KNOWLEDGE_API_BASE}/articles?${queryParams.toString()}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<ArticleListResponse>>(url);
      
      // 根据后端API响应格式调整
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        // 直接返回后端数据，不需要再次解包
        const articleList = backendData.data as ArticleListResponse;
        return {
          data: articleList.articles || [],
          total: articleList.total || 0,
          success: true,
          message: backendData.message || '获取文章列表成功'
        };
      } else {
        throw new Error(backendData.message || '获取文章列表失败');
      }
    } catch (error) {
      console.error('获取文章列表失败:', error);
      return {
        data: [],
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取文章列表失败'
      };
    }
  },

  // 创建文章
  async createArticle(articleData: Partial<Article>): Promise<ApiResponse<Article>> {
    if (shouldUseMockServer()) {
      return mockKnowledgeApi.createArticle(articleData);
    }
    try {
      const url = `${KNOWLEDGE_API_BASE}/articles`;
      const response = await http.post<BackendApiResponse<Article>>(url, articleData);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '文章创建成功'
        };
      } else {
        throw new Error(backendData.message || '文章创建失败');
      }
    } catch (error) {
      console.error('文章创建失败:', error);
      return {
        data: {} as Article,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '文章创建失败'
      };
    }
  },

  // 更新文章
  async updateArticle(articleId: number, articleData: Partial<Article>): Promise<ApiResponse<Article>> {
    if (shouldUseMockServer()) {
      return mockKnowledgeApi.updateArticle(articleId, articleData);
    }
    try {
      const url = `${KNOWLEDGE_API_BASE}/articles/${articleId}`;
      const response = await http.put<BackendApiResponse<Article>>(url, articleData);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '文章信息更新成功'
        };
      } else {
        throw new Error(backendData.message || '文章信息更新失败');
      }
    } catch (error) {
      console.error('文章信息更新失败:', error);
      return {
        data: {} as Article,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '文章信息更新失败'
      };
    }
  },

  // 删除文章
  async deleteArticle(articleId: number): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockKnowledgeApi.deleteArticle(articleId);
    }
    try {
      const url = `${KNOWLEDGE_API_BASE}/articles/${articleId}`;
      const response = await http.delete<BackendApiResponse<boolean>>(url);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: true,
          total: 1,
          success: true,
          message: backendData.message || '文章删除成功'
        };
      } else {
        throw new Error(backendData.message || '文章删除失败');
      }
    } catch (error) {
      console.error('文章删除失败:', error);
      return {
        data: false,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '文章删除失败'
      };
    }
  },

  // 获取分类列表
  async getCategories(): Promise<ApiResponse<Category[]>> {
    if (shouldUseMockServer()) {
      return mockKnowledgeApi.getCategories();
    }
    try {
      const url = `${KNOWLEDGE_API_BASE}/categories`;
      const response = await http.get<BackendApiResponse<CategoryListResponse>>(url);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data.categories || [],
          total: backendData.data.total || 0,
          success: true,
          message: backendData.message || '获取分类列表成功'
        };
      } else {
        throw new Error(backendData.message || '获取分类列表失败');
      }
    } catch (error) {
      console.error('获取分类列表失败:', error);
      return {
        data: [],
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取分类列表失败'
      };
    }
  },

  // 获取知识库统计
  async getKnowledgeStats(): Promise<ApiResponse<KnowledgeStats>> {
    if (shouldUseMockServer()) {
      return mockKnowledgeApi.getKnowledgeStats();
    }
    try {
      const url = `${KNOWLEDGE_API_BASE}/stats`;
      const response = await http.get<BackendApiResponse<KnowledgeStats>>(url);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '获取知识库统计成功'
        };
      } else {
        throw new Error(backendData.message || '获取知识库统计失败');
      }
    } catch (error) {
      console.error('获取知识库统计失败:', error);
      return {
        data: {} as KnowledgeStats,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取知识库统计失败'
      };
    }
  }
};